package com.combetter.changxing.viewmodel;

import android.app.Application;
import android.bluetooth.BluetoothGatt;
import android.content.Context;
import android.databinding.ObservableField;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;

import com.clj.fastble.data.BleDevice;
import com.combetter.changxing.Config;
import com.combetter.changxing.MyApp;
import com.combetter.changxing.net.FileDownLoadObserver;
import com.combetter.changxing.net.service.APIService;
import com.combetter.changxing.ui.activity.MineUpgradeActivity;
import com.combetter.changxing.util.CallBackUtils;
import com.combetter.changxing.util.LogUtil;
import com.combetter.changxing.util.ToastUtils;
import com.combetter.changxing.viewmodel.base.BaseViewModel;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import static com.combetter.changxing.util.EncryptUtils.desDecrypt;

/**
 * Created by 深圳唐龙飞讯科技有限公司 on 2018/6/12.
 */

public class MineUpgradeViewModel extends BaseViewModel {

    public ObservableField<String> localPath = new ObservableField<>();

    public MineUpgradeViewModel(@NonNull Application application) {
        super(application);

    }

    /**
     * 获取固件 版本列表
     */
    public void getFirmware( BleDevice bleDevice) {
        if (bleDevice == null || bleDevice.getMac() == null) {
            return;
        }
        try {
            String uid = MyApp.getInstance().getUserInfo().getUid();
            String identifier_id = bleDevice.getMac();
            mHttpRequest.createService(APIService.class)
                    .getFirmware(uid, identifier_id, 1)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeOn(Schedulers.io())
                    .subscribe(listHttpResult -> {
                        LogUtil.e("获取固件 ", listHttpResult);
                        if (listHttpResult.getCode() == 200) {
                            CallBackUtils.doCallBackMethod(listHttpResult.getData());
                        } else {
                            ToastUtils.error(listHttpResult.getMsg());
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void setUrl() {
    }


    /**
     * 下载单文件，可以是大文件，该方法不支持断点下载
     *
     * @param url                  下载网址
     * @param fileDownLoadObserver 监听回调
     */
    public Disposable downloadFile(Context context, String url, String version, final FileDownLoadObserver<File> fileDownLoadObserver) {
        return mHttpRequest.createService(APIService.class)
                .download2(Config.URL_BASE_FILE + url)
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .observeOn(Schedulers.computation())
                .map(responseBody -> fileDownLoadObserver.saveFile(context, responseBody, "wkzjOta" + version + ".bin"))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(file -> fileDownLoadObserver.onSuccess(file),
                        throwable -> fileDownLoadObserver.onFail(throwable),
                        () -> fileDownLoadObserver.onComplete());
    }

    /**
     * 更新
     *
     * @param view
     */
    public void update(View view) {
        if (((MineUpgradeActivity) view.getContext()).returnStatus() != BluetoothGatt.STATE_CONNECTED) {
            ToastUtils.showToastShort("设备断开连接，请重新连接");
            return;
        }
        if (TextUtils.isEmpty(this.localPath.get())) {
            ToastUtils.showToastShort("升级文件为空，请重新退出再进行下载");
            return;
        }
        byte[] firmware = readFirmware2(this.localPath.get().toString());
        if (firmware == null) {
            ToastUtils.showToastShort("升级文件为空，请重新退出再进行下载");
            return;
        }
        ((MineUpgradeActivity) view.getContext()).startOTA(firmware);
    }

    private byte[] readFirmware(String fileName) {
        try {
            InputStream stream = new FileInputStream(fileName);
            int length = stream.available();
            byte[] firmware = new byte[length];
            stream.read(firmware);
            stream.close();
            return firmware;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    private byte[] readFirmware2(String fileName) {
        try {
            byte rawKeyData1[] = "ZY%$ls19".getBytes("UTF-8");
            File file1 = new File(fileName);
            byte[] data = new byte[(int) file1.length()];
            FileInputStream is1 = new FileInputStream(file1);
            is1.read(data, 0, (int) file1.length());
            is1.close();
            // 加密
            byte[] dec = desDecrypt(data, rawKeyData1);
            return dec;
        }  catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}
